<?php

namespace app\api\controller;

use app\common\controller\Api;
//use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Auth as Auths;
use fast\Random;
use think\Cookie;
use think\Validate;
use think\Request;
use think\Db;
use think\Session;
use think\Cache;
use think\Image;
use Qiniu\Processing\ImageUrlBuilder;
use Qiniu\Processing\PersistentFop;


//引入七牛
/*引入SDK*/

use Qiniu\Auth as Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

/**
 * 会员接口
 */
class User extends Api
{
    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
//    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'sendcaptcha'];
    protected $noNeedLogin = '*';
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @param string $phone 账号
     * @param string $password 密码
     */
    public function login()
    {
        $mobile = $this->request->request('mobile');
        $password = $this->request->request('password');
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号格式不正确'));
        }
        if (!$mobile || !$password) {
            $this->error(__('手机号或密码不能为空'));
        }
        //$ret = $this->auth->login($mobile, $password);
        $salt = Random::alnum();
        //加密
        $password = $this->getEncryptPassword($password, $salt);
        $ret = Db::name('qz_user')->where(array('phone' => $mobile, 'password' => $password))->find();
        if ($ret) {
            //$data = ['userinfo' => $this->auth->getUserinfo()];
            Cookie::set('userid', $ret['userid']);
            $this->success(__('登录成功'));
        } else {
            $this->error(__('登录失败'));
        }
    }

//    /**
//     * 发送手机验证码
//     * @param string $mobile 手机号
//     */
//    public function sendcaptcha()
//    {
//        $mobile = $this->request->request('mobile');
//        if (!Validate::regex($mobile, "^1\d{10}$")) {
//            $this->error(__('手机号格式不正确'));
//        }
//        //$delcaptcha=Db::name('sms')->where('mobile',$mobile)->delete();
//
//        $send = Sms::send($mobile, '', 'sendcaptcha');
//        if ($send) {
//            $this->success(__('验证码已发送，有效期120分钟'));
//        } else {
//            $this->error(__('失败'));
//        }
//
//
//    }

    /**
     * 手机验证码注册
     *
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('无效格式'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号格式不正确'));
        }
        if (!$this->check($mobile, $captcha)) {
            $this->error(__('验证码不正确'));
        }
        //获取用户信息
        $user = Db::name('qz_user')->where('phone', $mobile)->find();
        if ($user) {
            //如果已经有账号则直接登录
            $this->error('用户已注册，请直接登录');
            //$ret = $this->auth->direct($user->id);
        } else {
            $this->success('ok');
        }
    }

    //用户注册填写密码
    public function pwd()
    {
        $pwd = $this->request->request('password', '', 'trim,strip_tags,htmlspecialchars');
        $newpwd = $this->request->request('new_password', '', 'trim,strip_tags,htmlspecialchars');
        $phone = $this->request->request('phone', '', 'trim,strip_tags,htmlspecialchars');
        $code = $this->request->request('code', '', 'trim,strip_tags,htmlspecialchars');
        if ($pwd != $newpwd) {
            $this->error('两次密码不相同');
        } else {
            //查询数据库是否有验证码信息
            $res = Db::name('qz_code')->where(array('phone' => $phone, 'code' => $code))->find();
            if ($res) {
                $salt = Random::alnum();
                //加密
                $qr_pwd = (new Auths())->getEncryptPassword($pwd, $salt);
                $data['phone'] = $phone;
                $data['password'] = $qr_pwd;
                $data['password'] = $pwd;
                $id = Db::name('qz_user')->insertGetId($data);
                $data['userid']=$this->idjiami();
                //获取ID
                if ($data['userid']) {
                    $code = Db::name('qz_code')->where(array('phone' => $phone, 'code' => $code))->find();
                    if ($code) {
                        //删除验证码数据
                        $de_code=Db::name('qz_code')->where('phone',$data['phone'])->find();
                        $this->success(__('成功'),$data);
                    } else {
                        $this->error('失败');
                    }
                } else {
                    $this->error('失败');
                }
            }else{
                $this->error('异常请求');
            }
        }
    }
    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     */

//    public function register(){
//        $phone = $this->request->request('phone');
//        $captcha = $this->request->request('captcha');
//        if (!Validate::regex($phone, "^1\d{10}$")) {
//            $this->error(__('手机号格式不正确'));
//        }
//        if (!$this->check($phone, $captcha)) {
//            $this->error(__('验证码不正确'));
//        }
//        $user=Db::name('qz_user')->where('phone',$phone)->find();
//        if($user){
//            $this->error(__('用户已注册，请直接登录'));
//        }
//        if (!$phone || !$captcha) {
//            $this->error(__('无效格式'));
//        }
////        if (!Sms::check($phone, $captcha, 'mobilelogin')) {
////            $this->error(__('无效参数'));
////        }
//        if ($user) {
//            //如果已经有账号则直接登录
//            $ret = $this->auth->direct($user->id);
//        } else {
//            $ret = $this->auth->register($phone, Random::alnum(), '', $phone, []);
//        }
//
//    }
//
//    /**
//     * 注册会员
//     *
//     * @param string $username 用户名
//     * @param string $password 密码
//     * @param string $email 邮箱
//     * @param string $mobile 手机号
//     */
//    public function register2()
//    {
//        $username = $this->request->request('username');
//        $password = $this->request->request('password');
//        $email = $this->request->request('email');
//        $mobile = $this->request->request('mobile');
//        if (!$username || !$password) {
//            $this->error(__('Invalid parameters'));
//        }
//        if ($email && !Validate::is($email, "email")) {
//            $this->error(__('Email is incorrect'));
//        }
//        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
//            $this->error(__('Mobile is incorrect'));
//        }
//        $ret = $this->auth->register($username, $password, $email, $mobile, []);
//        if ($ret) {
//            $data = ['userinfo' => $this->auth->getUserinfo()];
//            $this->success(__('Sign up successful'), $data);
//        } else {
//            $this->error($this->auth->getError());
//        }
//    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        $user->nickname = $nickname;
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }


    /**
     * 修改手机号
     *
     * @param string $email 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();
        //清空指定手机号验证码
        $this->flush($mobile);
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->request("type");
        $mobile = $this->request->request("mobile");
        $email = $this->request->request("email");
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error(__('失败'));
        }
    }

    /**
     * 登录后信息录入
     *
     * @param string $sex 性别
     * @param string $nickname 昵称
     * @param string $province 省
     * @param string $city 市
     * @param string $area 区
     * @param string $province 身高
     * @param string $province 体重
     */

    public function usexinxi()
    {
        //$id = $this->auth->id;
        $id = Session::get('userid');
        if ($id) {
            $data['sex'] = $this->request->request("sex");
            $data['nickname'] = $this->request->request("nickname");
            $data['province'] = $this->request->request("province");
            $data['city'] = $this->request->request("city");
            $data['area'] = $this->request->request("area");
            $data['height'] = $this->request->request("height");
            $data['weight'] = $this->request->request("weight");
            $save = Db::name("qz_user")->where('userid', $id)->save($data);
            if ($save) {
                $this->success(__('成功'));
            } else {
                $this->error(__('失败'));
            }
        }
    }

    /**
     * 我的个人资料展示
     */
    public function userdata()
    {
        //$id = $this->auth->id;
        $id = "42000001";
        //$id = Session::get('userid');
        if ($id) {
            $data['userinfo'] = Db::name('qz_user')->where('userid', $id)
                ->field('img,userid,nickname,province,city,sex,height,weight,introduct,
                                        prased,card_num,follow_id_str,follow_me_id_str,fs_num,gz_num')
                ->find();
            //查询我收藏的作品与获赞总数
            $count = Db::name('qz_works_like')->where(array('u_id' => $id, 'type' => 2))->count();
            $data['userinfo']['prased_sc'] = $data['userinfo']['prased'] + $count;
            //我发布的作品
            $data['works'] = Db::name('qz_works')->where('uid', $id)->where('pub_area', 1)
                ->field('id,title,praise_points,type,mus_or_video')
                ->select();
            foreach ($data['works'] as $k => $v) {
                if ($v['type'] == "1") {
                    $imgarr = json_decode($data['works']);
                    $data[$k][$v]['mus_or_video'] = $imgarr['0'];
                }
            }
            //我发布的作品总数
            $data['works'] = Db::name('qz_works')->where('uid', $id)->where('pub_area', 1)->count();
            $this->success(__('成功'), $data);
        }
    }

    /**
     * 我喜欢的作品展示
     */
    public function my_like_works()
    {
        $id = Session::get('userid');
        if ($id) {
            $data['userinfo'] = Db::name('qz_user')->where('userid', $id)
                ->field('img,userid,nickname,province,city,sex,height,weight,introduct,
                                        prased,card_num,follow_id_str,follow_me_id_str')
                ->select();
            //我喜欢的作品
            $data['like_works'] = Db::name('qz_works_like')->alias('a')
                ->join('qz_works b', 'a.w_id = b.id')
                ->field('a.id,a.w_id,b.title,b.praise_points,b.type,b.mus_or_video')
                ->where(array('u_id' => $id, 'type' => 1))
                ->select();
            //我喜欢的作品总数
            $data['like_count'] = Db::name('qz_works_like')->where(array('u_id' => $id, 'type' => 1))->count();
            $this->success(__('成功'), $data);
        }
    }

    /**
     * 我收藏的作品展示
     */
    public function my_sc_works()
    {
        $id = Session::get('userid');
        if ($id) {
            $data['userinfo'] = Db::name('qz_user')->where('userid', $id)
                ->field('img,userid,nickname,province,city,sex,height,weight,introduct,
                                        prased,card_num,follow_id_str,follow_me_id_str')
                ->select();
            //我收藏的作品
            $data['sc_works'] = Db::name('qz_works_like')->alias('a')
                ->join('qz_works b', 'a.w_id = b.id')
                ->field('a.id,a.w_id,b.title,b.praise_points,b.type,b.mus_or_video')
                ->where(array('u_id' => $id, 'type' => 2))
                ->select();
            //我收藏的作品总数
            $data['sc_count'] = Db::name('qz_works_like')->where(array('u_id' => $id, 'type' => 1))->count();
            $this->success(__('成功'), $data);
        }
    }

    /**
     * 我的个人资料修改
     */
    public function useredit()
    {
        //$id = $this->auth->id;
        $id = Session::get('userid');
        if ($id) {
            //用户信息
            $data['userinfo'] = Db::name('qz_user')->where('userid', $id)
                ->field('img,userid,nickname,sex,province,city,birthday,school,introduct')
                ->find();
            if ($this->request->isPost()) {
                $data['img'] = $this->request->request('img');
                $data['nickname'] = $this->request->request('nickname');
                $data['sex'] = $this->request->request('sex');
                $data['province'] = $this->request->request('province');
                $data['city'] = $this->request->request('city');
                $data['birthday'] = $this->request->request('birthday');
                $data['school'] = $this->request->request('school');
                $data['introduct'] = $this->request->request('introduct', '', 'htmlspecialchars');
                $save = Db::name('qz_user')->where('userid', $id)->save($data);
                if ($save) {
                    $this->success(__('成功'), $data);
                } else {
                    $this->error(__('失败'));
                }
            }
        }
    }

    /**
     * 我的作品删除
     */
    public function works_del()
    {
        //$id = $this->auth->id;
        $id = Session::get('userid');
        if ($id) {
            $wid = $this->request->request('id');
            if (!empty($wid)) {
                $del = Db::name('qz_works')->where(array('id' => $wid, 'uid' => $id))->delete();
                if ($del) {
                    $this->success(__('成功'));
                } else {
                    $this->error(__('失败'));
                }
            }
        }
    }

    /**
     * 我喜欢的作品删除
     */
    public function workslikes_del()
    {
        //$id = $this->auth->id;
        $id = Session::get('userid');
        if ($id) {
            $wid = $this->request->request('id');
            if (!empty($wid)) {
                $del = Db::name('qz_works_like')->where(array('id' => $wid, 'u_id' => $id, 'type' => 1))->delete();
                if ($del) {
                    $this->success(__('成功'));
                } else {
                    $this->error(__('失败'));
                }
            }
        }
    }

    /**
     * 我收藏的作品删除
     */
    public function scworks_del()
    {
        //$id = $this->auth->id;
        $id = Session::get('userid');
        if ($id) {
            $wid = $this->request->request('id');
            if (!empty($wid)) {
                $del = Db::name('qz_works_like')->where(array('id' => $wid, 'u_id' => $id, 'type' => 2))->delete();
                if ($del) {
                    $this->success(__('成功'));
                } else {
                    $this->error(__('失败'));
                }
            }
        }
    }

    /**
     * 绑定手机号
     */
    public function bindmobile()
    {
        //获取登录人id
        //$id = $this->auth->id;
        $id = Session::get('userid');
        if ($id) {
            $mobile = $this->request->request("mobile");
            $captcha = $this->request->request("captcha");
            if (!$mobile || !$captcha) {
                $this->error(__('手机号或验证码不能为空'));
            }
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('手机格式不正确'));
            }
            $isexist = Db::name('qz_user')->where('phone', $mobile)->find();
            if ($isexist) {
                $this->error(__('手机号已被绑定'));
            }
            if (!$this->check($mobile, $captcha)) {
                $this->error(__('验证码不正确'));
            }
            //修改用户绑定手机号的状态
            $data['is_binding'] = 1;
            $data['bind_phone'] = $mobile;
            $save = Db::name('qz_user')->where('userid', $id)->save($data);
            if ($save) {
                $this->success(__('成功'));
            } else {
                $this->error(__('失败'));
            }
        }
    }


    /**
     * app登录轮播图
     * type类型
     */
    public function login_banner()
    {
        $banner = Db::name('qz_app_banner')->where('type', 1)->select();

        if ($banner) {
            $this->success(__('成功'), $banner);
        } else {
            $this->error(__('失败'));
        }
    }

    /**
     * app首页广告轮播图
     * type类型（1，登录部分，2主页部分）
     */
    public function zy_banner()
    {
        $banner = Db::name('qz_works')->where('is_advert', 1)
            ->where('fb_status', 1)
            ->field('mus_or_video,id')
            ->find();
        //广告只能是图片
        foreach ($banner as $k => &$v) {
            $arr = json_decode($v['mus_or_video'], true);
            $v['mus_or_video'] = $arr['0'];
        }
        if ($banner) {
            $this->success(__('成功'), $banner);
        } else {
            $this->error(__('失败'));
        }
    }

    /**
     * 获取未读消息总数
     */
    public function unread_news()
    {
        $id = Session::get('userid');
        $count = Db::name('qz_news')->where('to_uid', $id)->where('state', 2)->count();
        $this->success(__('成功'), $count);
    }

    /**
     * 草稿箱
     */
    public function works_draft()
    {
        $id = Session::get('userid');
        if ($id) {
            $data = Db::name('qz_works')->where(array('uid' => $id, 'fb_status' => 2))
                ->field('title,content,releast_time,mus_or_video,type')
                ->select();
            if ($data) {
                $this->success(__('成功'), $data);
            } else {
                $this->error(__('失败'));
            }
        }
    }

    /**
     * 草稿箱删除
     */
    public function draft_del()
    {
        $id = Session::get('userid');
        if ($id) {
            //格式delete([1,2,3])
            $worksid = $this->request->request("id");
            if ($worksid) {
                $del = Db::name('qz_works')->where('id', $worksid)->delete($worksid);
                if ($del) {
                    $this->success(__('成功'));
                } else {
                    $this->error(__('失败'));
                }
            }
        }
    }

    /**
     * 达人认证页面数据展示
     */
    public function drauth()
    {
        $id = Session::get('userid');
        //查询作品量
        $data['w_count'] = Db::name('qz_works')->where('uid', $id)->count();
        //查询粉丝数量
        $data = Db::name('qz_user')->where('userid', $id)->field('fs_num,is_binding,is_id_card,rz_state')->select();
        if ($data) {
            $this->success(__('成功'), $data);
        } else {
            $this->error(__('失败'));
        }
    }

    /**
     * 达人和商家认证身份证页面数据展示
     */
    public function dr_idcard()
    {
        $id = Session::get('userid');
        if ($id) {
            $is_id_card = Db::name('qz_user')->where('userid', $id)
                ->value('is_id_card');
            if ($is_id_card == "1") {
                $data = Db::name('qz_user')->where('id', $id)
                    ->field('positive_id_card_img,back_id_card_img,hold_id_card_img,state')
                    ->select();
            }
            $data['is_id_card'] = $is_id_card;
            if ($data) {
                $this->success(__('成功'), $data);
            } else {
                $this->error(__('失败'));
            }
        } else {
            $this->error('异常访问');
        }

    }

    /**
     * 达人和商家认证身份证数据上传
     */

    public function id_card_uplode()
    {
        $id = Session::get('userid');
        if ($id) {
            //获取shuju
            $param = $this->request->param();
            if ($param) {
                //身份证正面
                $data['positive_id_card_img'] = trim($param['positive_id_card_img']);
                //身份证反面
                $data['back_id_card_img'] = trim($param['back_id_card_img']);
                //身份证手持
                $data['hold_id_card_img'] = trim($param['hold_id_card_img']);
                $data['rz_state'] = 1;
                $data['is_id_card'] = 1;
                $res = Db::name('qz_user')->where('userid', $id)->save($data);
                if ($res) {
                    $this->success('成功');
                } else {
                    $this->error('失败');
                }
            }
        } else {
            $this->error('异常请求');
        }
    }

    /**
     * 达人和商家认证数据提交
     */
    public function rz_form()
    {
        $id = Session::get('userid');
        if ($id) {
            //认证类型1,达人，2，商家
            $type = $this->request->param('type');
            //查询用户信息
            if ($type == '1') {
                $userinfo = Db::name('qz_user')->where('userid', $id)
                    ->field('fs_num,is_binding,is_id_card')
                    ->find();
                //作品总数
                $works_num = Db::name('qz_works')->where('uid', $id)->count();
                if ($works_num < 10) {
                    $this->error('失败，作品数少于10');
                } elseif ($userinfo['fs_num'] < 2000) {
                    $this->error('失败，粉丝数少于2000');
                } elseif ($userinfo['is_binding'] == 0) {
                    $this->error('失败，未绑定手机号');
                } elseif ($userinfo['is_id_card'] == 0) {
                    $this->error('失败，请先进行身份认证');
                } else {
                    $data['rz_state'] = 1;  //审核中
                    $data['rz_time'] = time();
                    $data['rz_type'] = 1;
                    $res = Db::name('qz_user')->where('userid', $id)->save($data);
                    if ($res) {
                        $this->success('成功');
                    } else {
                        $this->error('失败');
                    }
                }
            } elseif ($type == '2') {
                $param = $this->request->param();
                if ($param) {
                    $data['head_of_enterprise'] = trim($param['head_of_enterprise']);
                    $data['head_phone'] = trim($param['head_phone']);
                    $data['buyrz_adress'] = trim($param['buyrz_adress']);
                    $data['rz_state'] = 1;  //审核中
                    $data['rz_time'] = time();
                    $data['rz_type'] = 1;
                    $userinfo = Db::name('qz_user')->field('is_id_card,is_buy_rz')->where('userid', $id)->find();
                    if ($userinfo['is_id_card'] == "0") {
                        $this->error('失败，请先进行身份认证');
                    } elseif ($userinfo['is_buy_rz'] == "0") {
                        $this->error('失败，请先进行商家认证');
                    } else {
                        $res = Db::name('qz_user')->where('usrrid', $id)->save($data);
                        if ($res) {
                            $this->success('成功');
                        } else {
                            $this->error('失败');
                        }
                    }
                }
            }
        } else {
            $this->error('异常请求');
        }
    }

    /**
     * 商家认证信息获取
     */
    public function buy_card()
    {
        $id = Session::get('userid');
        $is_id_card = Db::name('qz_user')->where('uid', $id)
            ->value('is_id_card');
        if ($is_id_card == "1") {
            $data = Db::name('qz_user')->where('uid', $id)
                ->field('head_of_enterprise,head_phone,adress,is_id_card,rz_state')
                ->select();
        }
        $data['is_id_card'] = $is_id_card;
        if ($data) {
            $this->success(__('成功'), $data);
        } else {
            $this->error(__('失败'));
        }

    }

    /**
     * 商家营业执照信息获取
     */
    public function buy_zz()
    {
        $id = Session::get('userid');
        $is_id_card = Db::name('qz_buy_auth')->where('uid', $id)
            ->value('is_id_card');
        if ($is_id_card == "1") {
            $data = Db::name('qz_buy_auth')->where('uid', $id)
                ->field('business_license_img,other_img')
                ->select();
        }
        $data['is_id_card'] = $is_id_card;
        if ($data) {
            $this->success(__('成功'), $data);
        } else {
            $this->error(__('失败'));
        }
    }

    /**
     * 商家营业执照信息上传
     */
    public function buy_zz_uplode()
    {
        $id = Session::get('userid');
        if ($id) {
            $param = $this->request->param();
            $data['business_license_img'] = trim($param['business_license_img']);
            $data['other_img'] = trim($param['other_img']);
            $data['is_buy_rz'] = 1;
            $res = Db::name('qz_user')->where('userid', $id)->save($data);
            if ($res) {
                $this->success('成功');
            } else {
                $this->error('失败');
            }
        } else {
            $this->error('异常请求');
        }

    }

    /**
     * 合作关系，决策官，关于我们和各种协议
     * 1，注册协议，2，达人认证协议，3商家认证协议，4合作关系，5决策官，6关于我们
     */
    public function GVRP()
    {
        $type = $this->request->request("type");
        if ($type) {
            $data = Db::name('qz_app')->where('type', $type)->value('content');
            if ($data) {
                $this->success(__('成功'), $data);
            } else {
                $this->error(__('失败'));
            }
        }
    }

    /**
     * 意见反馈
     * problem  问题
     * contact  联系方式
     */
    public function feedback()
    {
        $data['id'] = Session::get('userid');
        $data['problem'] = $this->request->request("problem");
        $data['contact'] = $this->request->request("contact");
        if (empty($data['img'])) {
            $data['img'] = $this->request->request("img");
        }

        //上传图片
        $data['time'] = time();
        $res = Db::name('qz_feedback')->insert($data);
        if ($res) {
            $this->success(__('成功'));
        } else {
            $this->error(__('失败'));
        }
    }

    /**
     * 帮助与客服
     * type 类型 1，关于发布，2，申诉，举报，3账号问题，4店铺体验，5其他
     */
    public function help()
    {
        $list = Db::name('qz_help')
            ->field('problem,id,type')
            ->select();
        foreach ($list as $k => $v) {
            switch ($list[$k]['type']) {
                case 1:
                    $data['1'][$k] = $v;
                    break;
                case 2:
                    $data['2'][$k] = $v;
                    break;
                case 3:
                    $data['3'][$k] = $v;
                    break;
                case 4:
                    $data['4'][$k] = $v;
                    break;
                case 5:
                    $data['5'][$k] = $v;
                    break;
            }
        }
        //dump($data);
        if ($data) {
            $this->success(__('成功'), $data);
        } else {
            $this->error(__('失败'));
        }

    }

    /**
     * 帮助与客服单条查看
     */
    public function help_details()
    {
        $id = $this->request->request("id");
        if ($id) {
            $data = Db::name('qz_help')->where('id', $id)
                ->field('problem,answer')
                ->select();
            if ($data) {
                $this->success(__('成功'), $data);
            } else {
                $this->error(__('失败'));
            }
        }
    }

    /**
     * 帮助与客服有用或无用
     * type 类型（1，有用，2无用）
     */
    public function help_use()
    {
        $id = $this->request->request("id");
        $type = $this->request->request("type");
        if ($id) {
            if ($type = "1") {
                $data = Db::name('qz_help')->where('id', $id)
                    ->setInc('useful');
            } else if ($type == "2") {
                $data = Db::name('qz_help')->where('id', $id)
                    ->setInc('nouse');
            }
            if ($data) {
                $this->success(__('成功'));
            } else {
                $this->error(__('失败'));
            }
        }
    }

    /**
     * 获取用户体验卡数量
     */
    public function use_tycard()
    {
        $id = Session::get('userid');
        $data = Db::name('qz_tiyan_card')->where('uid', $id)->count();
        $this->success(__('成功'), $data);

    }

    /**
     * 分享获取体验卡
     */
    public function share_card()
    {
        $param = $this->request->param();
        $phone = trim($param['phone']);
        $userid = trim($param['userid']);
        if ($phone) {
            if (!Validate::regex($phone, "^1\d{10}$")) {
                $this->error(__('手机号格式不正确'));
            }
            $res = Db::name('qz_user')->where('phone', $phone)->where('status', 1)->value('phone');
            if ($res) {
                $this->error(__('该用户已注册'));
            }
            if ($userid != "") {
                //分享和被分享人各得两张体验卡
                //开始注册
                $res_fx = Db::name('qz_user')->where('');
            } else {
                $this->error(__('异常错误'));
            }
        }
        //判断用户是否已经注册
    }

    /**
     * 修改密码
     */
    public function edit_pwd()
    {
        $id = Session::get('userid');
        if ($this->request->isPost()) {
            $pwd = $this->request->request("password");
            $mobile = $this->request->request("mobile");
            $captcha = $this->request->request("captcha");
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('手机号格式不正确'));
            }
            if (!$this->check($mobile, $captcha)) {
                $this->error(__('验证码不正确'));
            }
            if ($pwd) {
                //随机字符串，
                $salt = Random::alnum();
                //加密
                $password = getEncryptPassword($pwd, $salt);
                $res = Db::name('qz_user')->where('userid', $id)->update(['password' => $password]);
                if ($res) {
                    $this->success(__('成功'));
                } else {
                    $this->error(__('失败'));
                }
            }
        } else {
            //查询用户手机号（登陆的手机号）
            $data['phone'] = Db::name('qz_user')->where('userid', $id)->value('phone');
            if ($data['phone']) {
                $this->success(__('成功'), $data);
            }

        }
    }


    /**
     * 我的消息
     * type 类型 1收藏,2获赞，3粉丝关注，4系统通知，5其他，
     * state 状态 1，已读，2未读
     */
    public function my_news()
    {
        $id = Session::get('userid');
//        $arr=[];
//        $arr['count']=0;
//        print_r($arr['count']);die;
        //收藏数未读消息条数
        $data['sc_count'] = Db::name('qz_news')->where(array('to_uid' => $id, 'type' => 1, 'state' => 2))
            ->count();
        //获赞数未读消息条数
        $data['hz_count'] = Db::name('qz_news')->where(array('to_uid' => $id, 'type' => 2, 'state' => 2))
            ->count();
        //粉丝未读消息条数
        $data['fs_count'] = Db::name('qz_news')->where(array('to_uid' => $id, 'type' => 3, 'state' => 2))
            ->count();
        //系统通知未读消息条数
        $data['xttz_count'] = Db::name('qz_news')->where(array('to_uid' => $id, 'type' => 4, 'state' => 2))
            ->count();
        //商家推送未读消息条数
        $data['buyts_count'] = Db::name('qz_news')->where(array('to_uid' => $id, 'type' => 5, 'state' => 2))
            ->count();
        //评论未读消息条数
        $data['pl_count'] = Db::name('qz_news')->where(array('to_uid' => $id, 'type' => 5, 'state' => 2))
            ->count();

        $this->success(__('成功'), $data);
    }

    /**
     * 我的消息详情
     * type 类型 1收藏2获赞，3粉丝关注，4系统通知，5其他,6评论和@
     * state 状态 1，已读，2未读
     */
    public function my_news_details()
    {
        $id = Session::get('userid');
        $type = $this->request->request('type');
        if ($type == "1") {
            $type = [1, 2];
            //修改未读的消息状态为已读
            $res = Db::name('qz_news')->where('type', 'in', $type)->where('state', 2)->update(['state' => '1']);
            $data = Db::name('qz_news')->alias('a')
                ->join('qz_works b', 'a.wid = b.id')
                ->join('qz_user c', 'a.form_uid = c.userid')
                ->where('to_uid', $id)
                ->where('type', 'in', $type)
                ->field('a.content,a.time,a.type,b.id,b.title,b.content AS bcontent,b.mus_or_video ,b.type AS btype,c.img,c.nickname')
                ->order('a.time desc')
                ->select();
        } else {
            //修改未读的消息状态为已读
            $res = Db::name('qz_news')->where('type', 'in', $type)->where('state', 2)->update(['state' => '1']);
            $data = Db::name('qz_news')->alias('a')
                ->join('qz_user b', 'a.form_uid = b.userid')
                ->where(array('to_uid' => $id, 'type' => $type))
                ->field('a.time,b.img,b.nickname')
                ->order('a.time desc')
                ->select();
        }
        if ($data) {
            $this->success(__('成功'), $data);
        } else {
            $this->error(__('失败'));
        }
    }

    /**
     * 发送手机验证码
     * @param string $mobile 手机号
     */
    public function code()
    {
        $phone = $this->request->request('phone');
        if ($phone) {
            $data["code"] = mt_rand(100000, 999999);
            $data["time"] = time();
            $data["phone"] = $phone;
            $time = 1;
            $post_data = array();
            $post_data['action'] = 'send';
            $post_data['userid'] = 321;
            $post_data['account'] = 'yilian';
            $post_data['password'] = 'yilian1';
            $post_data['content'] = "【大小圈资】" . $data["code"] . "该验证码" . $time . "分钟内有效，请尽快完成验证。";
            $post_data['mobile'] = $phone;
            $post_data['sendtime'] = '';
            $url = 'http://106.14.0.125:8088/sms.aspx';
            $o = '';
            foreach ($post_data as $k => $v) {
                $o .= "$k=" . urlencode($v) . '&';
            }
            $post_data = substr($o, 0, -1);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $result = curl_exec($ch);
            $result = json_decode($result, true);
            curl_close($ch);
            if ($result) {
                $res = Db::name('qz_code')->insert($data);
                $this->success(__('成功'), $data);
            } else {
                $this->error(__('失败'));
            }
        } else {
            $this->error(__('手机号不能为空'));
        }

    }

    /**
     * 校验验证码
     *
     * @param   int $mobile 手机号
     * @param   int $code 验证码
     * @param   int $exprie 有效期
     * @return  boolean
     */
    public function check($mobile, $code)
    {
        $exprie = 60;
        $time = time() - $exprie;
        //id降序得到最新的属于我的那一条验证码数据
        $sms = Db::name('qz_code')->where('phone', $mobile)
            ->order('id', 'DESC')
            ->find();
        if ($sms) {
            if ($sms['time'] > $time) {
                $correct = $code == $sms['code'];
                if (!$correct) {
                    $this->error(__('验证码不对'));
                } else {
//                    $result = Hook::listen('sms_check', $sms, null, true);
                    //成功则清空
                    //$this->flush($mobile);
                    $this->success(__('成功'));
                }
            } else {
                // 过期则清空该手机验证码
                $this->flush($mobile);
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 清空指定手机号验证码
     * @param   int $mobile 手机号
     * @return  boolean
     */
    public function flush($mobile)
    {
        Db::name('qz_code')->where('phone', $mobile)->delete();
        return true;
    }

    /**
     * 清除缓存
     */
    public function clear_cache()
    {
        rmdirs(CACHE_PATH, false);
        Cache::clear();
        $this->success('成功');
    }

    /**
     * 图片上传并压缩(限定压缩后不能小于2M)
     */
    /**
     * 上传图片
     * @return null|string
     */
    public function upload_img()
    {
        //dump($_FILES);
        if (empty($_FILES['img']['tmp_name'])) {
            $this->success('图片不合法');
        } else {
            // 要上传文件的临时文件
            $file = $_FILES['img']['tmp_name'];
            //echo $file;
            $pathinfo = pathinfo($_FILES['img']['name']);
            //dump($pathinfo);
            // 通过pathinfo函数获取图片后缀名
            $extension = array('png', 'jpg', 'jpeg', 'gif');
            $ext = $pathinfo['extension'];
            if (!in_array($ext, $extension)) {
                $this->success('图片格式有误');
            }
            $conf = config('Qiniu');
            //dump($conf);
            // 构建鉴权对象
            vendor('Qiniu.autoload');
            $auth = new Auth($conf['ACCESSKEY'], $conf['SECRETKEY']);
            //echo "1";die;
            // 生成上传需要的token
            $token = $auth->uploadToken($conf['BUCKET']);
            //echo "2";die;
            // 上传到七牛后保存的文件名
            $filename = date('Y') . '/' . date('m') . '/' . substr(md5($file), 8, 5) . date('Ymd') . rand(0, 9999) . '.' . $ext;
            //echo "3";die;

            // 初始化UploadManager类
            $uploadMgr = new UploadManager();
            //echo "4";die;
            list($res, $err) = $uploadMgr->putFile($token, $filename, $file);
            //echo "5";die;
            if ($err !== null) {
                return null;
            } else {
                //dump($res);die;
                //图片压缩
                $url = $conf['DOMAIN'] . "/" . $res['key'];            //图片的url地址


                //生成EncodedEntryURI的值
                $entry = $conf['BUCKET'] . ':' . $res['key'];//<Key>为生成缩略图的文件名
                //生成的值
                $encodedEntryURI = \Qiniu\base64_urlSafeEncode($entry);

                //使用SecretKey对新的下载URL进行HMAC1-SHA1签名
                //$newurl = $url."?imageView2/2/w/200/h/200|saveas/" . $encodedEntryURI;
                $newurl = $url . "?imageslim|saveas/" . $encodedEntryURI;
                $sign = hash_hmac("sha1", $newurl, $conf['SECRETKEY'], true);

                //对签名进行URL安全的Base64编码
                //$encodedSign = \Qiniu\base64_urlSafeEncode($sign);
                $encodedSign = $this->urlsafe_base64_encode($sign);
                //最终得到的完整下载URL
                //$finalURL =  $newurl . "/sign/" . $conf['ACCESSKEY'] . ":" . $encodedSign;
                $finalURL = $newurl . "/sign/" . $conf['ACCESSKEY'] . ":" . $encodedSign;
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $finalURL);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
                $dxycontent = curl_exec($ch);
                $arr = json_decode($dxycontent, true);
                //echo $arr['key'];  //压缩后的图片的图片名
                //获取图片的信息
                //新的图片地址
                $data['infourl'] = $url = $conf['DOMAIN'] . "/" . $arr['key'] . "?imageInfo";
                $info = json_decode($this->curl($data['infourl']));
                //dump($info);die;
                $size = $info->size;
                //计算数据大小范围(2M)
                $maxsize = 2 * 1024 * 1024;
                if ($size > $maxsize) {
                    $this->error('图片文件过大');
                    //删除云存储的图片
                    $this->del_image_video($arr['key']);
                } else {
                    $this->success(__('上传成功'), $data);

                }

            }
        }
    }


    /**
     * 删除七牛图片或视频
     * @param $delFileName 要删除的图片文件，与七牛云空间存在的文件名称相同
     * @return bool
     */
    public function del_image_video($delFileName)
    {
        //$delFileName="5.jpg";
        //echo "2";die;
        // 判断是否是图片  目前测试，简单判断
        $isImage = preg_match('/.*(\.png|\.jpg|\.jpeg|\.gif)$/', $delFileName);
        if (!$isImage) {
            return false;
        }
        $conf = config('Qiniu');

        // 构建鉴权对象
        vendor('Qiniu.autoload');
        $auth = new Auth($conf['ACCESSKEY'], $conf['SECRETKEY']);
        //echo "2";die;
        // 配置
        $config = new \Qiniu\Config();
        //echo "3";die;
        // 管理资源
        $bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
        //echo "4";die;
        // 删除文件操作
        $res = $bucketManager->delete($conf['BUCKET'], $delFileName);
        //dump($res);die;
        if (is_null($res)) {
            // 为null成功
            return true;
        }

        return false;

    }

    /**
     * 视频上传并压缩(限定压缩后40M)
     */
    public function uplode_video()
    {
        //dump($_FILES);die;
        if (empty($_FILES['video']['tmp_name'])) {
            $this->success('视频不合法');
        } else {
            // 要上传文件的临时文件
            $file = $_FILES['video']['tmp_name'];
            //echo $file;
            $pathinfo = pathinfo($_FILES['video']['name']);
            //dump($pathinfo);
            // 通过pathinfo函数获取图片后缀名
            $extension = array('mp3', 'mp4');
            $ext = $pathinfo['extension'];
            if (!in_array($ext, $extension)) {
                $this->success('图片格式有误');
            }
            $conf = config('Qiniu');
            //dump($conf);
            // 构建鉴权对象
            vendor('Qiniu.autoload');
            $auth = new Auth($conf['ACCESSKEY'], $conf['SECRETKEY']);
            //echo "1";die;
            // 生成上传需要的token
            $token = $auth->uploadToken($conf['BUCKET']);
            //echo "2";die;
            // 上传到七牛后保存的文件名
            $filename = date('Y') . '/' . date('m') . '/' . substr(md5($file), 8, 5) . date('Ymd') . rand(0, 9999) . '.' . $ext;
            //echo "3";die;

            // 初始化UploadManager类
            $uploadMgr = new UploadManager();
            //echo "4";die;
            list($res, $err) = $uploadMgr->putFile($token, $filename, $file);
            //echo "5";die;
            if ($err !== null) {
                return null;
            } else {
                //要转码的文件所在的空间和文件名。
                $video_name = $conf['DOMAIN'] . "/" . $res['key'];            //图片的url地址
                $key = $res['key'];
                //转码是使用的队列名称。 https://portal.qiniu.com/mps/pipeline
                $pipeline = $conf['pipeline'];
                $force = false;

                //转码完成后通知到你的业务服务器。
                $notifyUrl = 'http://192.168.31.182:80/api/User/notify';
                //$conf->useHTTPS=true;
                $pfop = new PersistentFop($auth, "");
                $bucket = $conf['BUCKET'];
                //要进行转码的转码操作。 http://developer.qiniu.com/docs/v6/api/reference/fop/av/avthumb.html
                $fops = "avthumb/mp4/s/640x360/vb/1.4m|saveas/" . \Qiniu\base64_urlSafeEncode($bucket . ":" . $res['key'] . "_qz");
                //echo $fops;
                list($id, $err) = $pfop->execute($bucket, $key, $fops, $pipeline, $notifyUrl, $force);
                echo "\n====> pfop avthumb result: \n";
                if ($err != null) {
                    var_dump($err);
                } else {

//                    $data['id']=$id;
//                    $data['url']=$video_name
                    //echo "PersistentFop Id: $id\n";
                    //$this->success('',$data);
                }
                //查询转码的进度和状态
                list($ret, $err) = $pfop->status($id);
                echo "\n====> pfop avthumb status: \n";
                if ($err != null) {
                    dump($err);
                    $this->error(__('上传失败'));
                } else {
                    dump($ret);
                    echo $ret['code'];
                    if ($ret['code'] == "1") {
                        //获取新的图片地址;
                        $zm_url = $conf['DOMAIN'] . "/" . $res['key'] . "_qz";
                        //获取压缩后视频的信息
                        $data['zm_url'] = $zm_url . "?avinfo";
                        //echo $data['zm_url'];
                        $vid_info = json_decode($this->curl($data['zm_url']));
                        dump($vid_info);
                        die;
                        $video_format = $vid_info->format;
                        $video_size = $video_format->size;
                        //最大视频限制
                        $maxsize = 50 * 1024 * 1024;
                        if ($video_size > $maxsize) {
                            $this->error(__('视频过大'));
                            //删除压缩前的视频
                            $this->del_image_video($video_name);
                            //删除压缩后的视频
                            $this->del_image_video($zm_url);
                        } else {
                            //删除压缩前的视频
                            $this->del_image_video($video_name);
                            $this->success(__('上传成功'));
                        }
                        //$this->del_image_video($video_name);
                    } elseif ($ret['code'] == "2") {
                        list($ret, $err) = $pfop->status($id);
                        echo "第二次";
                        dump($ret);
                        die;
                    } else {
                        $this->error(__('上传失败'));
                    }
                }
            }
        }
    }

    //压缩视频队列处理回调
    public function notify()
    {
        $conf = config('Qiniu');
        $accessKey = $conf['ACCESSKEY'];
        $secretKey = $conf['SECRETKEY'];
        $bucket = $conf['BUCKET'];
        // 构建鉴权对象
        vendor('Qiniu.autoload');
        $auth = new Auth($accessKey, $secretKey);
        //获取回调的body信息
        $callbackBody = file_get_contents('php://input');
        //回调的contentType
        $contentType = 'application/x-www-form-urlencoded';
        //回调的签名信息，可以验证该回调是否来自七牛
        $authorization = 'Authorization:QBox iN7NgwM31j4-BZacMjPrOQBs34UG1maYCAQmhdCV:tDK-3f5xF3SJYEAwsll5g= ';
        //七牛回调的url，具体可以参考：http://developer.qiniu.com/docs/v6/api/reference/security/put-policy.html
        //$url = 'http://172.30.251.210/upload_verify_callback.php';
        $url = 'http://192.168.31.182:80/api/User/notify';
        $isQiniuCallback = $auth->verifyCallback($contentType, $authorization, $url, $callbackBody);
        if ($isQiniuCallback) {
            $resp = array('ret' => 'success');
        } else {
            $resp = array('ret' => 'failed');
        }
        echo json_encode($resp);
    }

    /**
     * 视频转码
     *
     */
    public function zm_video()
    {
        $id = $this->request->request('id');
        $zm_url = $this->request->request('url');
        if ($id) {
            $conf = config('Qiniu');
            $auth = new Auth($conf['ACCESSKEY'], $conf['SECRETKEY']);
            $pfop = new PersistentFop($auth, "");
            //查询转码的进度和状态
            list($ret, $err) = $pfop->status($id);
            if ($err != null) {
                dump($err);
                $this->error(__('上传失败'));
            } else {
                dump($ret);
                echo $ret['code'];
                if ($ret['code'] == "1") {
                    //获取新的图片地址;
                    $zm_url = $conf['DOMAIN'] . "/" . $res['key'] . "_qz";
                    //获取压缩后视频的信息
                    $data['zm_url'] = $zm_url . "?avinfo";
                    //echo $data['zm_url'];
                    $vid_info = json_decode($this->curl($data['zm_url']));
                    dump($vid_info);
                    die;
                    $video_format = $vid_info->format;
                    $video_size = $video_format->size;
                    //最大视频限制
                    $maxsize = 50 * 1024 * 1024;
                    if ($video_size > $maxsize) {
                        $this->error(__('视频过大'));
                        //删除压缩前的视频
                        $this->del_image_video($video_name);
                        //删除压缩后的视频
                        $this->del_image_video($zm_url);
                    } else {
                        //删除压缩前的视频
                        $this->del_image_video($video_name);
                        $this->success(__('上传成功'));
                    }
                    //$this->del_image_video($video_name);
                } elseif ($ret['code'] == "2") {
                    list($ret, $err) = $pfop->status($id);
                    echo "第二次";
                    dump($ret);
                    die;
                } else {
                    $this->error(__('上传失败'));
                }
            }
        } else {
            $this->error(__('上传失败'));
        }

    }

    //base64位转码
    function urlsafe_base64_encode($data)
    {
        $data = base64_encode($data);
        $data = str_replace(array('+', '/'), array('-', '_'), $data);
        return $data;
    }

    //curl提交抓取
    public function curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $dxycontent = curl_exec($ch);
        return $dxycontent;
    }

    /**
     * 搜索用户和内容
     * type  类型(1--用户；2--内容)
     */
    public function search()
    {
        //获取用户id
        $id = Session::get('userid');
        //获取传递的参数，并过滤首尾空格
        $type = trim($this->request->request('type'));
        $str = trim($this->request->request('str'));
        //判断是否有传参
        if ($type != "" && $str != "") {
            if ($type == "1") {
                $data['list'] = Db::name('qz_user')->where('nickname', 'like', $str . '%')
                    ->field('img,nickname,userid,fs_num')
                    ->select();
            } elseif ($type == "2") {
                $data['list'] = Db::name('qz_works')->alias('a')
                    ->join('qz_user b', 'a.uid = b.userid')
                    ->where('a.title', 'like', $str . '%')
                    ->field('a.type,a.mus_or_video,a.title,b.img,b.userid,b.nickname,b.sex,b.height,b.weight')
                    ->limit(10)
                    ->select();
                //判断每篇文章是否被点赞过
                foreach ($data['list'] as $k => $v) {
                    $is_dz = Db::name('qz_works_dz')->where('wid', $v['wid'])
                        ->where('uid', $id)
                        ->value('id');

                    //有数据则已经点过赞，没有则没点过赞
                    if ($is_dz) {
                        $data['list'][$k]['is_dz'] = 1;
                    } else {
                        $data['list'][$k]['is_dz'] = 0;
                    }

                    //判断文章内容是图片还是视频
                    //为1是图片，截取第一张
                    if ($data['list'][$k]['type'] == "1") {
                        //json转数组
                        $imgarr = json_decode($v['mus_or_video'], true);
                        $data['list'][$k]['mus_or_video'] = $imgarr['0'];
                    }
                }
            }
            $data['str'] = $str;
            $this->success(__("成功"), $data);
        } else {
            $this->error(__("参数有误"));
        }
    }

    //加密的id生成
     function idjiami($id)
    {
        //根据id倒序查询数据库，取第一条数据得到数据库最后一条数据，+1得到添加后新的id，进行加密
        $user = Db::name('qz_user')->where('isdelete', 0)
            ->where('id',$id)
            ->value('id');
        //dump($user);die;
        $newid = $user + 1;
        //echo $newid;die;
        //此方法必须16位不同字符加密，so淘汰
        //$alphabetint = '1234567890';
        //$hashids = hashids(8,"tpadmin","1234567890123456789");
        //$encode_id = $hashids->encode($newid); //加密
        $encode_id = $this->alphaID($newid, false, 8);
        return $encode_id;
        //dump($user);die;
    }

    function alphaID($in, $to_num = false, $pad_up = false, $passKey = null)
    {
        $index = "0123456789";
        if ($passKey !== null) {
            // Although this function's purpose is to just make the
            // ID short - and not so much secure,
            // with this patch by Simon Franz (http://blog.snaky.org/)
            // you can optionally supply a password to make it harder
            // to calculate the corresponding numeric ID

            for ($n = 0; $n<strlen($index); $n++) {
                $i[] = substr( $index,$n ,1);
            }

            $passhash = hash('sha256',$passKey);
            $passhash = (strlen($passhash) < strlen($index))
                ? hash('sha512',$passKey)
                : $passhash;

            for ($n=0; $n < strlen($index); $n++) {
                $p[] =  substr($passhash, $n ,1);
            }

            array_multisort($p,  SORT_DESC, $i);
            $index = implode($i);
        }

        $base  = strlen($index);

        if ($to_num) {
            // Digital number  <<--  alphabet letter code
            $in  = strrev($in);
            $out = 0;
            $len = strlen($in) - 1;
            for ($t = 0; $t <= $len; $t++) {
                $bcpow = bcpow($base, $len - $t);
                $out   = $out + strpos($index, substr($in, $t, 1)) * $bcpow;
            }

            if (is_numeric($pad_up)) {
                $pad_up--;
                if ($pad_up > 0) {
                    $out -= pow($base, $pad_up);
                }
            }
            $out = sprintf('%F', $out);
            $out = substr($out, 0, strpos($out, '.'));
        } else {
            // Digital number  -->>  alphabet letter code
            if (is_numeric($pad_up)) {
                $pad_up--;
                if ($pad_up > 0) {
                    $in += pow($base, $pad_up);
                }
            }

            $out = "";
            for ($t = floor(log($in, $base)); $t >= 0; $t--) {
                $bcp = bcpow($base, $t);
                $a   = floor($in / $bcp) % $base;
                $out = $out . substr($index, $a, 1);
                $in  = $in - ($a * $bcp);
            }
            $out = strrev($out); // reverse
        }

        return $out;
    }
}
